extends Node2D

@onready var image: AnimatedSprite2D = $image
@onready var remain: RichTextLabel = $remain
@onready var timer: Timer = $timer

var type="shard"
var pos:Vector2i
var offset=Vector2i(1,0)
var layer:TileMapLayer
var shards
var heart
var sound
var game_scene
var inner_world
var cur_state="grey"
var cnt=0
var link={"line":null}
var cycle=6
var attack=4

func _ready() -> void:
	heart=get_tree().get_first_node_in_group("heart")
	layer=heart.layer_1
	game_scene=get_tree().get_first_node_in_group("game_scene")
	inner_world=get_tree().get_first_node_in_group("inner_world")
	sound=get_tree().get_first_node_in_group("sound")
	shards=get_parent()
	_change_state(cur_state)

func _change_state(new_state):
	cur_state=new_state
	image.play(cur_state)

func _setting(set_pos,set_layer,set_link):
	pos=set_pos
	layer=set_layer
	link=set_link
	self.global_position=layer.map_to_local(pos)

func _track():
	var others=shards.get_children()
	var other_pos=[]
	for i in others:
		if i!=self:
			other_pos.append(i.pos)
	var dis=heart.pos-pos
	if abs(dis.x)>abs(dis.y):
		if not dis.x:
			return
		var dir=Vector2i(dis.x/abs(dis.x),0)
		if pos+dir+offset in heart.path and pos+dir not in other_pos:
			pos+=dir
		else:
			if not dis.y:
				return
			dir=Vector2i(0,dis.y/abs(dis.y))
			if pos+dir+offset in heart.path and pos+dir not in other_pos:
				pos+=dir
			return
	else:
		if not dis.y:
			return
		var dir=Vector2i(0,dis.y/abs(dis.y))
		if pos+dir+offset in heart.path and pos+dir not in other_pos:
			pos+=dir
		else:
			if not dis.x:
				return
			dir=Vector2i(dis.x/abs(dis.x),0)
			if pos+dir+offset in heart.path and pos+dir not in other_pos:
				pos+=dir
			pass

func _show():
	if cnt<attack:
		_change_state("grey")
		if cnt==attack-1:
			remain.text="-"
		else:
			remain.text=str(attack-cnt-1)
		remain.set("theme_override_colors/default_color",Color(1.0,1.0,1.0))
	elif cnt<cycle:
		_change_state("gold")
		if cnt==cycle-1:
			remain.text="!"
		else:
			remain.text=str(cycle-cnt-1)
		remain.set("theme_override_colors/default_color",Color(0.0,0.0,0.0))
	
func _move():
	cnt=(cnt+1)%cycle
	_show()
	if cnt<attack:
		_wait()

func _wait():
	timer.start()

func _physics_process(delta: float) -> void:
	if heart.pos==pos:
		if cur_state=="grey":
			inner_world._reset()
		else:
			sound.play()
			global.cur_line=link["line"]
			global.cur_index=0
			game_scene._chat_in()
			self.queue_free()
	var targ=layer.map_to_local(pos)
	self.global_position=lerp(self.global_position,targ,0.3)

func _on_timer_timeout() -> void:
	_track()
